//
//  IMINetRequest.m
//  IMINet
//
//  Created by Travis on 09-11-23.
//  Copyright 2009 Exmart. All rights reserved.
//

#import "IMINetRequest.h"
#import <IMIBase/IMIBaseNSStringHelper.h>

@implementation IMINetRequest
@synthesize uuid,isGZip;

+ (id) requestWithURL:(NSURL*)theURL{
	return [[[self alloc] initWithURL:theURL] autorelease];
}
- (id) init
{
	self = [super init];
	if (self != nil) {
		MARK;
	}
	return self;
}

- (id) initWithURL:(NSURL *)theURL
{
	self = [super initWithURL:theURL];
	if (self != nil) {
		self.uuid=[NSString stringWithUUID];
		reqURL=[[theURL description] copy];
		bodyDict =[[NSMutableDictionary alloc] init];
	}
	return self;
}
- (id)initWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval{
	self = [super initWithURL:theURL cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
	if (self != nil) {
		self.uuid=[NSString stringWithUUID];
		reqURL=[[theURL description] copy];
		bodyDict =[[NSMutableDictionary alloc] init];
	}
	return self;
}
- (void) dealloc
{
	[bodyDict release];
	[reqURL release];
	[super dealloc];
}

- (void) setParam:(NSString*)param forKey:(NSString*)key{
	[bodyDict setObject:param forKey:key];
}
-(void) generate{
	if([[bodyDict allKeys] count]==0)return;
	
	NSMutableString *bodyString;
	bodyString=[NSMutableString string];
	for (int i=0;i< [[bodyDict allKeys] count];i++) {
		NSString *key=[[bodyDict allKeys] objectAtIndex:i];
		NSString *s;
		s=[NSString stringWithFormat:@"%@=%@",key,[bodyDict objectForKey:key]];
		if(i!=0){
			[bodyString appendFormat:@"&%@",s];
		}else {
			[bodyString appendString:s];
		}
	}
	
	if (isGZip) {
		[self setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
	}
	
	if([[self HTTPMethod] isEqualToString:@"POST"]){
		[self setHTTPBody:[NSData dataWithBytes:[bodyString UTF8String] length:[bodyString length]]];
	}else {
		[self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",reqURL,bodyString]]];
	}
}
@end
